package com.easylive.app.video.control;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.aliyun.player.nativeclass.MediaInfo;
import com.easylive.app.R;
import com.easylive.app.video.ScreenMode;
import com.easylive.app.video.TimeFormater;
import com.easylive.app.video.ViewAction;

import java.lang.ref.WeakReference;

/*
 * Copyright (C) 2010-2018 Alibaba Group Holding Limited.
 */

/**
 * 控制条界面。包括了顶部的标题栏，底部 的控制栏，锁屏按钮等等。是界面的主要组成部分。
 */

public class ControlView extends RelativeLayout implements ViewAction {

    private static final String TAG = ControlView.class.getSimpleName();
    private static final int WHAT_HIDE = 0;
    private static final int DELAY_TIME = 5 * 1000; //5秒后隐藏
    //标题，控制条单独控制是否可显示
    private boolean mTitleBarCanShow = true;
    private boolean mControlBarCanShow = true;
    private View mControlBar;
    //视频播放状态
    private PlayState mPlayState = PlayState.NotPlaying;
    //播放按钮
    private ImageView mPlayStateBtn;
    private ImageView mCtnterPlayStateBtn;
    //锁定屏幕方向相关
    // 屏幕方向是否锁定
    private boolean mScreenLocked = false;
    //大小屏公用的信息
    //视频信息，info显示用。
    private MediaInfo mAliyunMediaInfo;
    //播放的进度
    private int mVideoPosition = 0;
    //seekbar拖动状态
    private boolean isSeekbarTouching = false;
    //视频缓冲进度
    private int mVideoBufferPosition;
    private View mInfoBar;
    //当前位置文字
    private TextView mPositionText;
    //时长文字
    private TextView mDurationText;
    //进度条
    private SeekBar mSeekbar;
    //整个view的显示控制：
    //不显示的原因。如果是错误的，那么view就都不显示了。
    private HideType mHideType = null;
    //saas,还是mts资源,清晰度的显示不一样
    private boolean isMtsSource;
    //各种监听
    // 进度拖动监听
    private OnSeekListener mOnSeekListener;
    //标题返回按钮监听
    private OnBackClickListener mOnBackClickListener;
    //小屏按钮监听
    private OnSmallClickListener mOnSmallClickListener;
    //播放按钮点击监听
    private OnPlayStateClickListener mOnPlayStateClickListener;
    //大小屏按钮点击监听
    private OnScreenModeClickListener mOnScreenModeClickListener;
    //原视频时长
    private long mSourceDuration;
    private HideHandler mHideHandler = new HideHandler(this);

    public ControlView(Context context) {
        super(context);
        init();
    }

    public ControlView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ControlView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        //Inflate布局
        LayoutInflater.from(getContext()).inflate(R.layout.alivc_view_control, this, true);
        findAllViews(); //找到所有的view

        setViewListener(); //设置view的监听事件

        updateAllViews(); //更新view的显示
    }

    private void findAllViews() {
        mControlBar = findViewById(R.id.controlbar);
        mPlayStateBtn = (ImageView) findViewById(R.id.alivc_player_state);
        mCtnterPlayStateBtn = (ImageView) findViewById(R.id.alivc_player_state_center);

        mInfoBar = findViewById(R.id.alivc_info_bar);
        mSeekbar = (SeekBar) findViewById(R.id.alivc_info_seekbar);

        mInfoBar = findViewById(R.id.alivc_info_bar);
        mPositionText = (TextView) findViewById(R.id.alivc_info_position);
        mDurationText = (TextView) findViewById(R.id.alivc_info_duration);
        mSeekbar = (SeekBar) findViewById(R.id.alivc_info_seekbar);
    }

    private void setViewListener() {
        //控制栏的播放按钮监听
        mPlayStateBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnPlayStateClickListener != null) {
                    mOnPlayStateClickListener.onPlayStateClick();
                }
            }
        });
        //控制栏的播放按钮监听
        mCtnterPlayStateBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnPlayStateClickListener != null) {
                    mOnPlayStateClickListener.onPlayStateClick();
                }
            }
        });

        //seekbar的滑动监听
        SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {

                }

                if (mOnSeekListener != null) {
                    mOnSeekListener.onProgressChanged(progress, fromUser);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekbarTouching = true;

                mHideHandler.removeMessages(WHAT_HIDE);
                if (mOnSeekListener != null) {
                    mOnSeekListener.onSeekStart(seekBar.getProgress());
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mOnSeekListener != null) {
                    mOnSeekListener.onSeekEnd(seekBar.getProgress());
                }

                isSeekbarTouching = false;
                mHideHandler.removeMessages(WHAT_HIDE);
                mHideHandler.sendEmptyMessageDelayed(WHAT_HIDE, DELAY_TIME);
            }
        };
        //seekbar的滑动监听
        mSeekbar.setOnSeekBarChangeListener(seekBarChangeListener);
    }

    /**
     * 是不是MTS的源 //MTS的清晰度显示与其他的不太一样，所以这里需要加一个作为区分
     *
     * @param isMts true:是。false:不是
     */
    public void setIsMtsSource(boolean isMts) {
        isMtsSource = isMts;
    }

    /**
     * 设置是否显示控制栏
     *
     * @param show fase：不显示
     */
    public void setControlBarCanShow(boolean show) {
        mControlBarCanShow = show;
        updateAllControlBar();
    }

    /**
     * 设置当前屏幕模式：全屏还是小屏
     *
     * @param mode {@link ScreenMode#Small}：小屏. {@link ScreenMode#Full}:全屏
     */
    @Override
    public void setScreenModeStatus(ScreenMode mode) {
        updateInfoBar();
    }

    /**
     * 判断当前播放进度是否在中间广告位置
     */
//    private boolean isVideoPositionInMiddle(int mVideoPosition){
//        if(mAdvPosition == MutiSeekBarView.AdvPosition.ALL
//                || mAdvPosition == MutiSeekBarView.AdvPosition.START_END
//                || mAdvPosition == MutiSeekBarView.AdvPosition.START_MIDDLE){
//            return (mVideoPosition >= mSourceDuration / 2 + mAdvDuration) && (mVideoPosition <= mSourceDuration / 2 + mAdvDuration);
//        }else{
//            return mVideoPosition >= mSourceDuration / 2 && mVideoPosition <= mSourceDuration / 2;
//        }
//    }

    /**
     * 设置当前的播放状态
     *
     * @param playState 播放状态
     */
    public void setPlayState(PlayState playState) {
        mPlayState = playState;
        updatePlayStateBtn();
    }

    /**
     * 设置视频信息
     *
     * @param aliyunMediaInfo 媒体信息
     * @param currentQuality  当前清晰度
     */
    public void setMediaInfo(MediaInfo aliyunMediaInfo, String currentQuality) {
        mAliyunMediaInfo = aliyunMediaInfo;
        updateInfoBar();
    }

    /**
     * 获取视频进度
     *
     * @return 视频进度
     */
    public int getVideoPosition() {
        return mVideoPosition;
    }

    /**
     * 更新视频进度
     *
     * @param position 位置，ms
     */
    public void setVideoPosition(int position) {
        mVideoPosition = position;
        updateInfoBar();
    }

    private void updateAllViews() {
        updatePlayStateBtn();//更新播放状态
        updateInfoBar();//更新屏的显示信息
        updateAllControlBar();//更新控制栏显示
    }

    /**
     * 更新控制条的显示
     */
    private void updateAllControlBar() {
        //单独设置可以显示，并且没有锁屏的时候才可以显示
        boolean canShow = mControlBarCanShow && !mScreenLocked;
        if (mControlBar != null) {
            mControlBar.setVisibility(canShow ? VISIBLE : INVISIBLE);
        }
    }

    /**
     * 更新小屏下的控制条信息
     */
    private void updateInfoBar() {
        //先设置小屏的info数据
        if (mAliyunMediaInfo != null) {
            mDurationText.setText(TimeFormater.formatMs(mAliyunMediaInfo.getDuration()));
            mSeekbar.setMax((int) mAliyunMediaInfo.getDuration());
        } else {
            mDurationText.setText(TimeFormater.formatMs(0));
            mSeekbar.setMax(0);
        }

        if (isSeekbarTouching) {
            //用户拖动的时候，不去更新进度值，防止跳动。
        } else {
            mSeekbar.setSecondaryProgress(mVideoBufferPosition);
            mSeekbar.setProgress(mVideoPosition);
            mPositionText.setText(TimeFormater.formatMs(mVideoPosition));
        }
    }

    /**
     * 更新播放按钮的状态
     */
    private void updatePlayStateBtn() {
        if (mPlayState == PlayState.NotPlaying) {
            mCtnterPlayStateBtn.setVisibility(VISIBLE);
            mCtnterPlayStateBtn.setImageResource(R.mipmap.beauty_player_play_selected);
            mPlayStateBtn.setImageResource(R.mipmap.beauty_video_icon_play);
        } else if (mPlayState == PlayState.Playing) {
            mCtnterPlayStateBtn.setVisibility(GONE);
            mPlayStateBtn.setImageResource(R.mipmap.beauty_video_icon_stop);
        }
    }

    /**
     * 监听view是否可见。从而实现5秒隐藏的功能
     */
    @Override
    protected void onVisibilityChanged(@Nullable View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE) {
            //如果变为可见了。启动五秒隐藏。
            hideDelayed();
        }
    }

    public void setHideType(HideType hideType) {
        this.mHideType = hideType;
    }

    private void hideDelayed() {
        mHideHandler.removeMessages(WHAT_HIDE);
        mHideHandler.sendEmptyMessageDelayed(WHAT_HIDE, DELAY_TIME);
    }

    /**
     * 重置状态
     */
    @Override
    public void reset() {
        mHideType = null;
        mAliyunMediaInfo = null;
        mVideoPosition = 0;
        mPlayState = PlayState.NotPlaying;
        isSeekbarTouching = false;
        updateAllViews();
    }

    /**
     * 显示画面
     */
    @Override
    public void show() {
        if (mHideType == HideType.End) {
            //如果是由于错误引起的隐藏，那就不能再展现了
            setVisibility(GONE);
//            hideQualityDialog();
        } else {
            updateAllViews();
            setVisibility(VISIBLE);
        }
    }

    /**
     * 隐藏画面
     */
    @Override
    public void hide(HideType hideType) {
        if (mHideType != HideType.End) {
            mHideType = hideType;
        }
        setVisibility(GONE);
    }

    /**
     * 设置当前缓存的进度，给seekbar显示
     *
     * @param mVideoBufferPosition 进度，ms
     */
    public void setVideoBufferPosition(int mVideoBufferPosition) {
        this.mVideoBufferPosition = mVideoBufferPosition;
        updateInfoBar();
    }

    public void setOnScreenModeClickListener(OnScreenModeClickListener l) {
        mOnScreenModeClickListener = l;
    }

    public void setOnBackClickListener(OnBackClickListener l) {
        mOnBackClickListener = l;
    }

    public void setOnSmallClickListener(OnSmallClickListener l) {
        mOnSmallClickListener = l;
    }

    public void setOnSeekListener(OnSeekListener onSeekListener) {
        mOnSeekListener = onSeekListener;
    }

    public void setOnPlayStateClickListener(OnPlayStateClickListener onPlayStateClickListener) {
        mOnPlayStateClickListener = onPlayStateClickListener;
    }

    public void setDetails() {
        mInfoBar.setVisibility(GONE);
    }

    public void setLikeDetails() {
        mInfoBar.setVisibility(GONE);
    }


    /**
     * 播放状态
     */
    public static enum PlayState {
        /**
         * Playing:正在播放
         * NotPlaying: 停止播放
         */
        Playing, NotPlaying
    }


    public interface OnScreenModeClickListener {
        /**
         * 大小屏按钮点击事件
         */
        void onClick();
    }

    public interface OnBackClickListener {
        /**
         * 返回按钮点击事件
         */
        void onClick();
    }

    public interface OnSmallClickListener {
        /**
         * 切换小屏按钮点击事件
         */
        void onClick();
    }


    public interface OnSeekListener {
        /**
         * seek结束事件
         */
        void onSeekEnd(int position);

        /**
         * seek开始事件
         */
        void onSeekStart(int position);

        /**
         * seek进度改变事件
         */
        void onProgressChanged(int progress, boolean fromUser);
    }


    public interface OnPlayStateClickListener {
        /**
         * 播放按钮点击事件
         */
        void onPlayStateClick();
    }

    /**
     * 隐藏类
     */
    private static class HideHandler extends Handler {
        private WeakReference<ControlView> controlViewWeakReference;

        public HideHandler(ControlView controlView) {
            controlViewWeakReference = new WeakReference<ControlView>(controlView);
        }

        @Override
        public void handleMessage(Message msg) {

            ControlView controlView = controlViewWeakReference.get();
            if (controlView != null) {
                if (!controlView.isSeekbarTouching) {
                    // controlView.hide(HideType.Normal);
                }
            }

            super.handleMessage(msg);
        }
    }

}
